package com.example.lib_mvp.musicService;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.Toast;


import com.example.lib_mvp.Constant;
import com.tjf.lib_utils.EventBusUtils;
import com.tjf.lib_utils.LogsUtils;

public class GlobalMediaPlayer {
    private static GlobalMediaPlayer instance;
    private MediaPlayer mediaPlayer;
    private Context context;

    private GlobalMediaPlayer(Context context) {
        this.context = context.getApplicationContext();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 播放完成时的回调
                EventBusUtils.sendEvent(Constant.MusicStatus, "播放完毕");
                Toast.makeText(context, "播放完成", Toast.LENGTH_SHORT).show();
            }
        });

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // 播放错误时的回调
//                Toast.makeText(context, "播放错误", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    public static synchronized GlobalMediaPlayer getInstance(Context context) {
        if (instance == null) {
            instance = new GlobalMediaPlayer(context);
        }
        return instance;
    }

    public void play(String url) {
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.reset();
            }
            mediaPlayer.setDataSource(context, Uri.parse(url));
            mediaPlayer.prepareAsync(); // 异步准备
            LogsUtils.i("开始播放==Uri.parse(url)="+Uri.parse(url));
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    LogsUtils.i("开始播放===");
                    mediaPlayer.start();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
    }

    public void stop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.reset();
            }
        }
    }

    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            instance = null;
        }
    }
}
